package com.ruoyi.information.service.back.impl;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.information.domain.back.ArticleBack;
import com.ruoyi.information.mapper.back.ArticleBackMapper;
import com.ruoyi.information.mapper.back.RecomBackMapper;
import com.ruoyi.information.service.back.IArticleBackService;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.PathVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 资讯Service业务层处理
 *
 * @author ruoyi
 * @date 2023-05-02
 */
@Service
public class ArticleBackServiceImpl implements IArticleBackService {
    @Autowired
    private ArticleBackMapper articleMapper;
    @Autowired
    private RemoteFileService remoteFileService;
    @Autowired
    private RecomBackMapper recomBackMapper;

    /**
     * 查询资讯
     *
     * @param id 资讯主键
     * @return 资讯
     */
    @Override
    public ArticleBack selectArticleById(Long id) {
        return articleMapper.selectArticleById(id);
    }

    /**
     * 查询资讯列表
     *
     * @param article 资讯
     * @return 资讯
     */
    @Override
    public List<ArticleBack> selectArticleList(ArticleBack article) {
        return articleMapper.selectArticleList(article);
    }

    /**
     * 新增资讯
     *
     * @param article 资讯
     * @return 结果
     */
    @Override
    public int insertArticle(ArticleBack article) {
        article.setReleaseTime(DateUtils.getNowDate());
        article.setCreateTime(DateUtils.getNowDate());
        return articleMapper.insertArticle(article);
    }

    /**
     * 修改资讯
     *
     * @param article 资讯
     * @return 结果
     */
    @Override
    public int updateArticle(ArticleBack article) {
        article.setUpdateTime(DateUtils.getNowDate());

        /*删除云资源*/
        if (article.getCover() != null) {
            ArticleBack main = articleMapper.selectArticleById(article.getId());
            if (main.getCover() != null) {
                CloudClassroomBackServiceImpl.comparePhoto(main.getCover(), article.getCover(), remoteFileService);
            }
        }

        return articleMapper.updateArticle(article);
    }

    /**
     * 批量删除资讯
     *
     * @param ids 需要删除的资讯主键
     * @return 结果
     */
    @Override
    public int deleteArticleByIds(Long[] ids) {
        /*删除云资源*/
        List<String> photos = articleMapper.selectArticleListPhotos(ids);
        if (photos != null) {
            remoteFileService.delete(new PathVo(photos), SecurityConstants.FROM_SOURCE);
        }
        recomBackMapper.deleteRecomByIdsAndType(ids,"资讯");
        return articleMapper.deleteArticleByIds(ids);
    }

    /**
     * 删除资讯信息
     *
     * @param id 资讯主键
     * @return 结果
     */
    @Override
    public int deleteArticleById(Long id) {
        return articleMapper.deleteArticleById(id);
    }
}
